package suzf.top.kotlinjava.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.metadata.IPage
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import suzf.top.kotlinjava.common.entity.User;
import suzf.top.kotlinjava.common.mapper.UserMapper;
import suzf.top.kotlinjava.service.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import suzf.top.kotlinjava.common.exception.ServiceException
import suzf.top.kotlinjava.service.model.TestUserModel
import javax.annotation.Resource

/**
 *  用户表 服务实现类
 *========================
 * Created with IntelliJ IDEA
 * Author: Mr.Su
 * Blog: https://suzf.top/
 * Date: 2019-10-10
 * ========================
 */
@Service
class UserServiceImpl : ServiceImpl<UserMapper, User>(), UserService {

    @Resource
    lateinit var userMapper: UserMapper

    /**
     * 查询全部
     */
    @Throws(ServiceException::class)
    override fun selectAll(): IPage<User>? {

        //return userMapper.selectAll()
        val page = Page<User>(1, 10)
        return userMapper.selectPage(page, null)
    }

    /**
     *
     */
    @Throws(ServiceException::class)
    override fun selectAll1(): MutableList<TestUserModel> {
        return userMapper.selectAll1()
    }

    /**
     *  根据id查询
     */
    @Throws(ServiceException::class)
    override fun findOneById(id: Int): User? {
/*        val user = userMapper.findOneById(id)
        if (user == null) {
            throw ServiceException("用户不存在")
        }else {
            return user
        }*/

        val wrapper = QueryWrapper<User>()
        wrapper.eq("id", id)
        val user2 = userMapper.selectOne(wrapper)
        if (user2 == null) {
            throw ServiceException("用户不存在")
        } else {
            return user2
        }
    }

    /**
     *  根据用户名查询
     */
    @Throws(ServiceException::class)
    override fun findOneByUserName(userName: String): User? {
        val user = userMapper.findOneByUserName(userName)
        if (user == null) {
            throw ServiceException("用户不存在")
        } else {
            return user
        }
    }

    /**
     *  根据ID删除
     */
    @Throws(ServiceException::class)
    override fun deleteById(id: Int) {
        userMapper.deleteById(id)
    }

    /**
     *  添加用户
     */
    @Throws(ServiceException::class)
    override fun insertUser(user: User) {
        val userSql = userMapper.findOneById(user.id!!)
        if (userSql != null) {
            throw ServiceException("用户已存在")
        } else {
            userMapper.insert(user)
        }
    }
}
